package com.example.designpatterns.interpreter.parser;

import com.example.designpatterns.interpreter.Expression;
import com.example.designpatterns.interpreter.nonterminal.AddExpression;
import com.example.designpatterns.interpreter.nonterminal.MultiplyExpression;
import com.example.designpatterns.interpreter.nonterminal.SubtractExpression;
import com.example.designpatterns.interpreter.terminal.NumberExpression;
import com.example.designpatterns.interpreter.terminal.VariableExpression;

import java.util.Stack;

/**
 * 表达式解析器 - 将简单的数学表达式字符串解析为表达式树
 * 支持基本的加减乘运算和变量
 * 注意：这是一个简化的解析器，仅支持简单的表达式，不支持复杂的优先级和括号
 */
public class ExpressionParser {
    
    /**
     * 解析简单的后缀表达式字符串
     * 例如: "a b +" 表示 a + b
     * @param expression 后缀表达式字符串
     * @return 解析后的表达式树
     */
    public Expression parse(String expression) {
        Stack<Expression> stack = new Stack<>();
        String[] tokens = expression.split("\\s+");
        
        for (String token : tokens) {
            if (token.equals("+")) {
                Expression right = stack.pop();
                Expression left = stack.pop();
                stack.push(new AddExpression(left, right));
            } else if (token.equals("-")) {
                Expression right = stack.pop();
                Expression left = stack.pop();
                stack.push(new SubtractExpression(left, right));
            } else if (token.equals("*")) {
                Expression right = stack.pop();
                Expression left = stack.pop();
                stack.push(new MultiplyExpression(left, right));
            } else {
                // 尝试解析为数字，如果不是数字则视为变量
                try {
                    int value = Integer.parseInt(token);
                    stack.push(new NumberExpression(value));
                } catch (NumberFormatException e) {
                    stack.push(new VariableExpression(token));
                }
            }
        }
        
        return stack.pop();
    }
} 